<?php

namespace Es;

use Es\Struct\ConnectStruct;
use Es\Exceptions\CommonExceptions;
use Elasticsearch\{ClientBuilder,Client as EsClient};

class Client {

    protected static $client;

    /**
     * @throws CommonExceptions
     */
    public function __construct(ConnectStruct $connect)
    {
        if(!is_object(self::$client) || !self::$client->ping()){

            $ClientBuilder = ClientBuilder::create()->setHosts($connect->host);

            if(!empty($connect->name) && !empty($connect->password)){
                $ClientBuilder->setBasicAuthentication($connect->name, $connect->password);
            }     
            try{
                self::$client = $ClientBuilder->build();
            }catch(\Throwable $e){
                throw new CommonExceptions($e->getMessage(), $e->getCode());
            }
        }
           
    }
    public function getOriginClient() : EsClient
    {
        return self::$client;
    }
}